<template>
	<view class="new_page">
		<view class="main">
			<view class="form_wrap">
				<uni-forms :modelValue="formData">
					<view class="div_box">
						<uni-forms-item label="活动名称">
							<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text"
								v-model="formData.eventName" placeholder="输入..." />
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="活动原价">
							<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text"
								v-model="formData.eventPrice" placeholder="输入..." />
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="活动折扣价">
							<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text"
								v-model="formData.eventDiscountPrice" placeholder="输入..." />
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="开始时间">
							<uni-datetime-picker v-model="formData.eventStartDate" return-type="string" :hide-second="true">
								<view class="pp text-right">
									<text v-if="formData.eventStartDate">{{formData.eventStartDate}}</text>
									<text v-else>选择开始时间</text>
								</view>
							</uni-datetime-picker>
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="结束时间">
							<uni-datetime-picker v-model="formData.eventEndDate" return-type="string" :hide-second="true">
								<view class="pp text-right">
									<text v-if="formData.eventEndDate">{{formData.eventEndDate}}</text>
									<text v-else>选择结束时间</text>
								</view>
							</uni-datetime-picker>
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="活动规则">
							<!-- <uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text" v-model="formData.eventRule"
								placeholder="输入..." /> -->
							<my-editor v-model="formData.eventRule"></my-editor>
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="活动介绍" name="job">
							<!-- <uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text"
								v-model="formData.eventDetail" placeholder="输入..." /> -->
								<my-editor v-model="formData.eventDetail"></my-editor>
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="适用门店">
							<!-- <uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text"
								v-model="formData.eventShop" placeholder="输入..." /> -->
								<!-- <my-editor v-model="formData.eventShop"></my-editor> -->
								<view class="pp" @click="toggle('bottom')">
									<view v-if="formData.eventShop" class="s_item">
										<view v-for="(i,index) in mdShowList" :key="index" class="ii">
											<text>{{i.city}}—{{i.storeName}}</text>
										</view>
									</view>
									<text v-else>选择适用门店</text>
								</view>
						</uni-forms-item>
					</view>
					<view class="div_box">
						<uni-forms-item label="适用时间">
							<uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text"
								v-model="formData.eventTime" placeholder="输入..." />
						</uni-forms-item>
					</view>
					
					<view class="div_box">
						<uni-forms-item label="系统下架日期">
							<uni-datetime-picker v-model="formData.eventDueDate" return-type="string" :hide-second="true">
								<view class="pp text-right">
									<text v-if="formData.eventDueDate">{{formData.eventDueDate}}</text>
									<text v-else>选择系统下架日期</text>
								</view>
							</uni-datetime-picker>
						</uni-forms-item>	
					</view>

					<view class="div_box">
						<uni-forms-item label="是否支持付款">
							<!-- <uni-easyinput :placeholderStyle="placeholderStyle" :inputBorder="false" type="text"
								v-model="formData.payAble" placeholder="输入..." /> -->
								<radio-group @change="(e)=>{formData.payAble=e.detail.value}">
									<view class="r_item">
										<label class="r_item" v-for="(item,index) in checkFk" :key="index">
											<view class="weui-cell__hd">
												<radio :value="item.id" color="#2865b8" :checked="!!(formData.payAble==item.id)||item.check"/>
											</view>
											<view class="weui-cell__bd">{{item.value}}</view>
										</label>
									</view>
								</radio-group>
						</uni-forms-item>
					</view>
					
					
					<view class="div_box">
						<uni-forms-item label="活动图片" label-position="top">
							<uni-file-picker v-model="imageValue" fileMediatype="image" mode="grid" :auto-upload="false"
								@select="select" @delete="deleteImg" />
						</uni-forms-item>
					</view>
				</uni-forms>
			</view>

		</view>
		<view class="fix_btn">
			<!-- goToPage('/pages/actAdd/actAdd') :class="['btn-r',isActive?'b-bg':'b-grey-bg']"-->
			<button :class="['btn-r',isActive?'b-bg':'b-grey-bg']" s @click="actAdd">
				<text>{{id?'保存修改':'新增活动'}}</text>
			</button>
		</view>
		
		
		<!-- 选择门店 -->
		<uni-popup ref="popup" background-color="#fff" :type="type">
			<view class="popup-content">
				<view class="title">
					<text class="text">选择门店</text>
				</view>
				<view class="md_wrap">
					<checkbox-group @change="checkboxChange">
						<label class="weui-cell md_item" v-for="(item,index) in mdList" :key="index">
							<view class="weui-cell__hd">
								<checkbox :value="item.id" :checked="item.check" color="#2865b8"/>
							</view>
							<view class="weui-cell__bd">{{item.city}}—{{item.storeName}}</view>
						</label>
					</checkbox-group>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { upLoadImg,addAct,getMenDian,getActListById } from '@/request/api.js'
	import { toast,useRouter } from '@/request/utils.js'
	export default {
		data() {
			return {
				isActive: false,
				placeholderStyle: "font-size: 28rpx;text-align:right",
				formData: {
					eventName: '',
					eventDiscountPrice: '',
					eventPrice: '',
					eventDetail: '',
					eventRule: '',
					eventShop: '',
					eventTime: '',
					eventImageList: '',
					eventStartDate: '',
					eventEndDate: '',
					eventDueDate: '',
					payAble: 'N'
				},
				// {url:"https://img.qianchazhijia.com/reborn/beijing/1.png"}
				imageValue: [],
				imageValueTemp: [],
				checkFk: [
					{value: "是", id:'Y', check: false},
					{value: "否", id:'N', check: false},
				],
				mdList: [], // 门店列表
				id: null,
			}
		},
		onLoad(params){
			this.id = params.id;
			uni.setNavigationBarTitle({
			  title: this.id ? '修改活动':'新增活动'
			})
			if(!this.id){return}
			getActListById({id:this.id}).then((res)=>{
				if(res.code==200){
					this.minxiFormData(res.data)
				}
			})
		},
		watch: {
			formData: {
				handler: function(newValue, oldValue) {
					let arr = Object.values(this.formData);
					let bol = arr.every((item)=>{
						return typeof item != 'object' ? !!item : !!(item&&item.length>0);
					})
					this.isActive = bol;
				},
				deep: true,
				immediate: true,
			}
		},
		computed: {
			mdShowList(){
				let showArr = [];
				let arr = this.formData.eventShop&&this.formData.eventShop.split(",");
				if(arr){
					for(let j=0;j<arr.length;j++){
						for(let i=0;i<this.mdList.length;i++){
							if(this.mdList[i].id==arr[j]){
								this.mdList[i].check = true;
								showArr.push(this.mdList[i]);
								break;
							}
						}
					}
				}
				return showArr;
			}
		},
		mounted(){
			this.getMenDian();
		},
		methods: {
			// 获取单条数据整合现在formData
			minxiFormData(data){
				// let { eventDetail,eventDiscountPrice } = data
				// this.formData = Object.assign(this.formData,data);
				for(let key in this.formData){
					this.formData[key] = data[key];
				}
				console.log(this.formData.eventImageList)
				this.imageValueTemp = data.eventImageList.split(";");
				this.imageValue = this.imageValueTemp.map((item)=>{
					return {
						url: item
					}
				})
				console.log(this.formData.eventImageList,this.imageValue)
			},
			checkboxChange(e){
				console.log(e)
				this.formData.eventShop = e.detail.value.join(",");
				console.log(this.formData.eventShop)
			},
			toggle(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type)
			},
			// 适用门店
			async getMenDian(){
				let res = await getMenDian();
				if(res.code==200){
					this.mdList = res.data.map((item)=>{
						item.check = false;
						return item;
					});
					console.log(this.mdList)
				}
			},
			// 获取上传状态
			select(e) {
				console.log('选择文件：', e);
				this.imageValueTemp.push(...e.tempFilePaths);
				this.formData.eventImageList = this.imageValueTemp.join(";")
			},
			deleteImg(e){
				console.log(e)
				let index = this.imageValueTemp.indexOf(e.tempFilePath);
				this.imageValueTemp.splice(index,1);
				this.formData.eventImageList = this.imageValueTemp.join(";")
			},
			// 添加活动
			async actAdd(){
				console.log(this.formData)
				if(!this.isActive){
					toast('请完善数据填写')
					return;
				}
				// 上传图片
				let resArr = await this.upLoadImg();
				if(resArr.length>0){
					this.formData.eventImageList = resArr.map((res)=>{
						return res.data;
					}).join(";");
					console.log(this.formData.eventImageList)
				}
				let data = JSON.parse(JSON.stringify(this.formData))
				// return
				if(this.id){
					data.id = this.id;
				}
				// 添加活动
				let res = await addAct(data);
				
					if(!this.id){
						if(res.code==200){
							// 无id是新增
							uni.showModal({
								title: '添加成功',
								content: '是否继续添加?',
								success: (res)=> {
									if (res.confirm) {
										this.formData = {
											eventName: '',
											eventDiscountPrice: '',
											eventPrice: '',
											eventDetail: '',
											eventRule: '',
											eventShop: '',
											eventTime: '',
											eventImageList: [],
											eventStartDate: '',
											eventEndDate: '',
											eventDueDate: ''
										};
										this.imageValue = [];
									}
									if(res.cancel){
										this.goToPage('/pages/actCenter/actCenter','navigateBack');
									}
								}
							})
						}else{
							toast('请重新检查数据')	
						}
								
					}else{
						if(res.code==200){
								// 修改完成重新修正formData
								getActListById({id:this.id}).then((res)=>{
									if(res.code==200){
										this.minxiFormData(res.data)
									}
								})
								// 有id是修改
								uni.showModal({
									title: '修改成功',
									content: '是否继续修改?',
									cancelText: '返回',
									success: (res)=> {
										if (res.confirm) {}
											
										if(res.cancel){
											this.goToPage('/pages/actCenter/actCenter','navigateBack');
										}
									}
								})
									
						}else{
							toast('请先进行修改')
						}
						
					}
			},
			// 修改活动
			
			// 上传图片
			async upLoadImg(){
				let allPromise = [];
				if(this.imageValueTemp.length>0){
					for(let i=0;i<this.imageValueTemp.length;i++){
						// 图片临时路径
						let path = this.imageValueTemp[i];
						// 临时路径才上传
						if(path.includes('tmp')){
							allPromise.push(upLoadImg(path, 'image'))
						}else{
							allPromise.push(
								Promise.resolve({
									data: path
								})
							)
						}
						
					}
				}
				return await Promise.all(allPromise);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.pp {
		padding: 20rpx 0;
		text-align: right;
	}
	.r_item {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin-left: 20rpx;
	}
	.new_page {
		width: 699.28rpx;
		padding-top: 30rpx;
		margin: auto;
		padding-bottom: 160rpx;

		.main {
			padding: 0 20rpx 20rpx;
			background-color: #fff;
			border-radius: 20rpx;
		}

		.form_wrap {
			/deep/.uni-forms-item__content {
				padding: 20rpx 0;
				border-bottom: 1px solid $line-grey;

				input {
					text-align: right;
				}
			}

			/deep/.uni-forms-item__label {
				font-size: 28rpx !important;
			}
			.s_item {
				box-sizing: border-box;
				width: 100%;
				display: flex;
				justify-content: flex-end;
				flex-wrap: wrap;
				.ii {
					margin: 0 10rpx;
					padding: 6rpx 10rpx;
					border: 1rpx solid $main-color;
					color: $main-color;
					margin-bottom: 10rpx;
				}
			}
		}
	}

	.fix_btn {
		// position: fixed;
		width: 90%;
		left: 0;
		right: 0;
		margin: auto;
		margin-top: 50rpx;
		bottom: 40rpx;
		z-index: 10;
	}
	
	.popup-content {
		height: 400rpx;
		padding: 30rpx;
		overflow: auto;
		.title {
			font-size: 34rpx;
			
		}
		.md_wrap {
			padding: 30rpx 0;
			box-sizing: border-box;
			width: 100%;
			/deep/ checkbox-group  {
				box-sizing: border-box;
				width: 100%;
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
			}
			.md_item {
				box-sizing: border-box;
				width: 48%;
				display: flex;
				align-items: flex-start;
				white-space: pre-wrap;
				word-break: break-all;
				margin-bottom: 10rpx;
			}
		}
	}
</style>